class Criteria

  def initialize(query, column)
    @query = query
    @name = column.name
    @type = column.type
    @op = ''
    @value = ''
  end

  def name
    @name
  end

  def name?
    if not query.foreign_keys[@name].nil?
      return query.foreign_keys[@name][:alias]
    end
    @name
  end

  def foreign?
    not query.foreign_keys[@name].nil?
  end

  def foreign_collection
    query.foreign_keys[@name][:collection]
  end

  def type
    @type
  end

  def value
    @value
  end

  def values_list
    if foreign?
      @value
    else
      [@value]
    end
  end

  def op
    @op
  end

  def operator
    @op
  end

  def query
    @query
  end

  def from(request)
    @op = request["#{@name}_operation"]
    @value = request["#{@name}_value"]
  end

  def sql_value
    values = @value
    if not foreign?
      values = [@value]
    end

    if values.nil?
      values = []
    end

    sql_values = []
    values.each do |value|
      alone_val = ''
      if @type==:integer
        alone_val = "#{value}"
      end
      if @type==:string or @type==:text
        if @op=='like'
          alone_val = "\"%#{value}%\""
        else
          alone_val = "\"#{value}\""
        end
      end
      sql_values<<alone_val
    end

    if foreign?
      sql_value = "(#{sql_values.join(',')})"
    else
      sql_value = sql_values[0]
    end
    return sql_value
  end

  def to_sql
    sql_condition = ""
    act_operator = @op.clone
    if not act_operator.nil? and act_operator!=''# and @sql_value.nil?
      if foreign?
        act_operator.gsub!('!=','not in')
        act_operator.gsub!('=','in')
      end
      sql_condition = "#{@name} #{act_operator} #{sql_value}"
    end
    return sql_condition
  end

end
